import {messages} from "share/common";
import React,{Component} from 'react';
import Info from 'components/info';
import airUtil from './air-ticket-columns';
import AdvanceTable from 'components/advanced-table';
import AirTicketServer from './air-ticket-server';
import {Button, Icon, Modal, Input} from 'antd';
import 'styles/supplier-management/air-ticket-quotation/air-ticket-quotation-detail.scss';
import SlideFrame from 'components/slide-frame';
import AddQuotationContent from "./add-quotation-content";;
const TextArea = Input.TextArea;

class AirTicketQuotationDetail extends Component{
  constructor(props){
    super(props);
    this.state = {
      baseData: {},
      otherData: {},
      otherAttr: [],
      currentRecord: {},
      baseAttr: airUtil.getBaseInfoAttr(),
      isAdd: true, // 是否是新建
      showSlideFrame: false, // 是否显示侧滑
      showModal: false, // 是否显示预订失败原因弹框
      failReason: '', // 失败原因
      isInit: false // 是否已经初始化，处理使接口仅调用一次
    }
    this.resData = {}; // 后端返回数据
    this.rfpId = this.props.params.id;
    this.certificateTypeList = [
      {
        value: 0,
        description: messages('supplier.key1067')/*身份证*/
      },
      {
        value: 1,
        description: messages('supplier.key1068')/*护照*/
      },
      {
        value: 2,
        description: messages('supplier.key1069')/*港澳通行证*/
      },
      {
        value: 3,
        description: messages('supplier.key1070')/*台湾通行证*/
      },
      {
        value: 4,
        description: messages('supplier.key1071')/*台胞证*/
      },
      {
        value: 5,
        description: messages('supplier.key1072')/*回乡证*/
      }
    ];
  }

  createJounryOption = () => {
    const option = {
      key: 'flightRfpJourneyVos',
      service: ()=>{return this.advanceTableServer('flightRfpJourney')},
      pagination: null,
      rowKey: (record,index) => record.id || index,
      columns: airUtil.getJourneyColumns(),
      bordered: true,
    }
    return option;
  }

  createPassengersOption = () => {
    const option = {
      key: 'passengers',
      service: ()=>{return this.advanceTableServer('passengers')},
      pagination: null,
      index: true,
      rowKey: (record,index) => record.id || index,
      columns: airUtil.getPassengersColumn(),
      bordered: true,
    }
    return option;
  }

  createQuotationOption = () => {
    const option = {
      key: 'quotationSchemes',
      tableName: 'quotationSchemes',
      showUtils: true,
      service: ()=>{return this.advanceTableServer('quotationSchemes')},
      pagination: null,
      index: true,
      onRef: this.advanceTableRef,
      rowKey: (record,index) => record.id || index,
      columns: airUtil.getQuotationColumn(this.onOperator),
      bordered: true,
      defaultExpandAllRows: true,
      expandedRowRender: this.renderExpandRow
    }
    return option;
  }

  onOperator = (type, record) => {
    let status = null;
    switch (type) {
      case 'detail': this.setState({currentRecord: record, showSlideFrame: true});
      break;
      case 'delete':
        status = 'DELETE';
        break;
      case 'stop':
        status = 'DEACTIVATE';
        break;
      case 'fail':
        this.record = record;
        this.setState({showModal: true})
        break;
      case 'success':
        status = 'SUCCESS';
        break;
    }
    if(status){
      AirTicketServer(this).quotationChangeStatus(record.id, status).then(res => {
        if(res.status === 200){
          this.resData = {};
          this.tableRef.getList();
        }
      })
    }
  }

  onChangeStatusFail = () => {
    let status = 'FAILURE';
    const {failReason} = this.state;
    AirTicketServer(this).quotationChangeStatus(this.record.id, status, failReason).then(res => {
      if(res.status === 200){
        this.resData = {};
        this.tableRef.getList();
      }
    });
    this.setState({showModal: false});
  }

  onReasonChange = (eve) => {
    this.setState({failReason: eve.target.value});
  }

  renderExpandRow = (record) => {
    if(!record.confirmTime){
      return messages('supplier.key1073')/*暂无确认信息*/;
    }
    let name = record.confirmUserName;
    let confirmDate = record.confirmTime;
    let confirmPassengers = record.confirmPassengers || [];
    let gender = {
      MALE: messages('supplier.key1082')/*男*/,
      FEMALE: messages('supplier.key1083')/*女*/,
    }
    return (
      <div>
        <h4>{messages('supplier.key1074',{arg1: name,arg2: confirmDate})/*用户{arg1}于{arg2}确认该方案，请及时预订，以免耽误客人出行*/}</h4>
        {
          confirmPassengers.map((item, index) => {
            let cardType = this.certificateTypeList[item.certificateType].description || '';
            let people = `${index+1}姓：${item.givenName}，名：${item.surName}`;
            let tip = messages('supplier.key1084',{arg1: people,arg2: cardType,arg3: item.certificateCode,arg4: gender[item.gender],arg5: item.certificateExpiration||'-',arg6: item.nationality||'-'})/*乘机人 {arg1}，证件类型：{arg2}，证件号：{arg3}，性别：{arg4}，证件到期日期：{arg5}，国籍：{arg6}*/
            return (
              <div key={item.id}>
                <p className='expand-tip'>{tip}</p>
              </div>
            )
          })
        }
      </div>
    );
  }

  advanceTableRef = (ref) => {
    this.tableRef = ref;
  }

  advanceTableServer = (attrName) => {
    if(this.resData.status === 200){
      let promise = new Promise((resolve)=>{
        resolve(JSON.parse(JSON.stringify(this.resData)));
      });
      return promise.then(res=>{
        res.data.rows = res.data.body[attrName];
        return res;
      });
    }else{
      return AirTicketServer(this).getDetailData(this.rfpId).then(res => {
        this.resData = res;
        this.setState({baseData: res.data.body.flightRfp, isInit: true});
        this.setOtherData(res.data.body);
        res.data.rows = res.data.body[attrName];
        return res;
      })
    }
  }

  setOtherData = (body) => {
    let other = body['costCenters'];
    let attr = [];
    let data = {};
    if(other && other.length > 0){
      other.forEach((item, index) => {
        attr.push({title: item.name, dataIndex: `name${index}`});
        data[`name${index}`] = item.value;
      })
    }
    this.setState({otherData: data, otherAttr: attr});
  }

  onAddQuotation = () => {
    this.setState({showSlideFrame: true});
  }

  onAfterClose = (str) => {
    this.setState({showSlideFrame: false, currentRecord: {}});
    if(str === 'update'){
      this.resData = {};
      this.tableRef.getList();
    }
  }

  render () {
    const {failReason, isInit, baseData, baseAttr, showModal, otherData, otherAttr, showSlideFrame, isAdd, currentRecord} = this.state;
    return (
      <div className='air-ticket-quotation-detail'>
        <Info
          title={messages('supplier.key977')/*基础信息*/}
          dataSource={baseData}
          attributes={baseAttr}
        />
        <div className='info-title' style={{marginTop: 32}}>{messages('supplier.key903')/*行程信息*/}</div>
        { isInit && (<AdvanceTable.SimpleTable {...this.createJounryOption()}/>)}
        <div className='info-title'>{messages('supplier.key978')/*乘客信息*/}</div>
        { isInit && (<AdvanceTable.SimpleTable {...this.createPassengersOption()}/>)}
        {
          otherAttr.length > 0 && (
            <Info
              title={messages('supplier.key341')/*其他信息*/}
              dataSource={otherData}
              attributes={otherAttr}
            />
          )
        }
        <div
          className='info-title'
          style={{marginTop: otherAttr.length > 0 ? 32 : 0}}
        >
          {messages('supplier.key979')/*已报价方案信息*/}
        </div>
        <Button
          type='primary'
          onClick={this.onAddQuotation}
        >
          <Icon type="plus" />{messages('supplier.key980')/*添加报价*/}
        </Button>
        <AdvanceTable.SimpleTable {...this.createQuotationOption()}/>
        <div className='quotation-detail-footer'>
          <Button onClick={()=>{window.history.go(-1)}}>___返回___</Button>
        </div>
        {
          showSlideFrame && (
            <SlideFrame
              title={isAdd ? messages('supplier.key980')/*添加报价*/ : messages('supplier.key981')/*报价详情*/}
              show={showSlideFrame}
              content={AddQuotationContent}
              params={{rfpId: this.rfpId, ...currentRecord}}
              afterClose={this.onAfterClose}
              onClose={() => this.setState({ showSlideFrame: false, currentRecord: {} })}
            />
          )
        }
        {
          showModal && (
            <Modal
              visible={showModal}
              width={800}
              title={messages('supplier.key1085')/*请输入预订失败原因*/}
              onCancel={() => this.setState({showModal: false})}
              footer={[
                <Button onClick={()=>{this.setState({showModal: false})}}>{messages('common.cancel'/*取消*/)}</Button>,
                <Button disabled={!failReason} type="primary" onClick={this.onChangeStatusFail}>{messages('common.ok'/*确定*/)}</Button>
              ]}>
                <TextArea placeholder={messages('common.please.input')/*请输入*/} value={failReason} onChange={this.onReasonChange}/>
            </Modal>
          )
        }
      </div>
    )
  }
}

export default AirTicketQuotationDetail;
